import { actionClient } from '@/api'
/**
 * 鉴权
 */
export default {
  namespaced: true,
  state: {
    token: localStorage.getItem('token') || null,
    currentUser: JSON.parse(localStorage.getItem('user') || 'null') || null,
    roles: []
  },
  mutations: {
    setToken(state, { token }) {
      state.token = token
      if (token === null) {
        localStorage.removeItem('token')
      } else {
        localStorage.setItem('token', token)
      }
      console.log(token)
    },
    setCurrentUser(state, { user, roles = [] }) {
      state.currentUser = user
      state.roles = roles
      if (user === null) {
        localStorage.removeItem('user')
      } else {
        localStorage.setItem('user', JSON.stringify(user))
      }
    }
  },
  actions: {
    async loginCode({ commit }, code) {
      const { token } = await actionClient.post('auth', code)
      commit('setToken', { token })
      const user = await actionClient.get('me')
      commit('setCurrentUser', { user })
    },
    async login({ commit }, data) {
      const { token } = await actionClient.post('auth', data)
      commit('setToken', { token })
      const user = await actionClient.get('me')
      commit('setCurrentUser', { user })
    },
    async loginWeChat({ commit }, data) {
      const { token } = await actionClient.post('login-qrcode', data)
      commit('setToken', { token })
      const user = await actionClient.get('me')
      commit('setCurrentUser', { user })
    },
    logout({ commit }) {
      commit('setToken', { token: null })
      commit('setCurrentUser', { user: null })
    },
    async update(_, payload) {
      await actionClient.post('me', payload)
    }
  }
}
